package dhm.com.dhmshop.updata.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.dhmshop.R;
import dhm.com.dhmshop.adapter.mine.FunctionAdapter;
import dhm.com.dhmshop.adapter.mine.ShowImageAdapter;
import dhm.com.dhmshop.adapter.order.ChildOrderAdapter;
import dhm.com.dhmshop.base.BaseActiity;
import dhm.com.dhmshop.base.Presenter.PressenterImpl;
import dhm.com.dhmshop.base.netWork.Constant;
import dhm.com.dhmshop.base.netWork.LoginContract;
import dhm.com.dhmshop.entity.Bean;
import dhm.com.dhmshop.entity.FunctionBean;
import dhm.com.dhmshop.entity.GetAllOrder;
import dhm.com.dhmshop.entity.Result;
import dhm.com.dhmshop.entity.ResultDetailCallback;
import dhm.com.dhmshop.utils.BitmapUtil;
import dhm.com.dhmshop.utils.SpUtils;
import dhm.com.dhmshop.view.mine.order.ShowevaluateActivity;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;

public class GoodsfunctionActivity extends BaseActiity implements LoginContract.IView {


    @BindView(R.id.order_id)
    TextView orderId;
    @BindView(R.id.ordertime)
    TextView ordertime;
    @BindView(R.id.nameshop)
    CheckBox nameshop;
    @BindView(R.id.recy)
    RecyclerView recy;
    @BindView(R.id.allmoney)
    TextView allmoney;
    @BindView(R.id.yunfei)
    TextView yunfei;
    @BindView(R.id.jifen)
    TextView jifen;
    @BindView(R.id.text_type)
    TextView text_type;
    @BindView(R.id.realmoney)
    TextView realmoney;
    @BindView(R.id.edit_count)
    EditText editCount;
    @BindView(R.id.recy_image)
    RecyclerView recyImage;
    private PressenterImpl pressenter;
    private ShowImageAdapter showImageAdapter;
    private List<String> goods_images=new ArrayList<>();
    private ArrayList<Bitmap> image = new ArrayList<>();
    private ArrayList<String> mSelectPath;
    private String typeid = "";
    private FunctionBean functionBean;
    private PopupWindow popWindow;
    private FunctionAdapter functionAdapter;
    
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    private static final int REQUEST_IMAGE = 2;
    private GetAllOrder.DataBean bean;

    @Override
    protected int getLayout() {
        return R.layout.activity_goodsfunction;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

        bean = (GetAllOrder.DataBean) getIntent().getSerializableExtra("bean");
        LinearLayoutManager manager=new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        ChildOrderAdapter childOrderAdapter=new ChildOrderAdapter(this);

        showImageAdapter = new ShowImageAdapter(image, this);
        showImageAdapter.setaddClick(new ShowImageAdapter.OnIntentClick() {
            @Override
            public void item() {
                pickImage();
            }
        });
        showImageAdapter.setdeleteClick(new ShowImageAdapter.OnClick() {
            @Override
            public void item(int posttion) {
                if (goods_images==null||goods_images.size()<posttion){
                    image.remove(posttion-goods_images.size());
                }else {
                    goods_images.remove(posttion);
                }
                showImageAdapter.setList(goods_images);
                showImageAdapter.showImage(image);
            }
        });


        recy.setAdapter(childOrderAdapter);
        recy.setLayoutManager(manager);
        recyImage.setLayoutManager(gridLayoutManager);
        recyImage.setAdapter(showImageAdapter);
        childOrderAdapter.setImageList(bean.getList());

        float price=0;

        for (int i = 0; i< bean.getList().size(); i++){
            price=price+Float.parseFloat(bean.getDeliverMoney())+(Float.parseFloat(bean.getList().get(i).getGoodsPrice())* Integer.parseInt(bean.getList().get(i).getGoodsNum()));
        }

        allmoney.setText("￥ "+price);

        yunfei.setText("￥ "+ bean.getDeliverMoney());

        realmoney.setText("￥ -"+ bean.getRealTotalMoney());

        orderId.setText(bean.getOrderNo()+"");

        ordertime.setText(bean.getCreateTime());



    }

    @Override
    protected void initData() {
        showPopwindow();
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof FunctionBean) {
            functionBean = (FunctionBean) data;
            functionAdapter.setShopList(functionBean.getData());
        }else if (data instanceof Bean){
            Bean bean= (Bean) data;
            Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
            if (bean.getCode()==1){
                finish();
            }



        }
    }

    @Override
    public void fail(String error) {

    }

    @OnClick({R.id.back, R.id.question, R.id.commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.question:
                setBackgroundAlpha(0.5f);
                popWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.commit:
                String content = editCount.getText().toString();
                if (content==null||content.equals("")){
                    Toast.makeText(this, "请填写投诉内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (typeid.equals("")) {
                    Toast.makeText(GoodsfunctionActivity.this, "请选择取消订单的原因", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, File> files = new HashMap<>();
                try {
                    for (int i = 0; i < image.size(); i++) {
                        files.put(bitmapToString(image.get(i)), new File(bitmapToString(image.get(i))));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String uid = SpUtils.getString(this, "uid");
                if (files.size()==0){
                    Map<String,String> map=new HashMap<>();
                    map.put("token",Constant.TOKEN);
                    map.put("orderId",bean.getOrderId()+"");
                    map.put("complainType",typeid);
                    map.put("complainContent",content);
                    map.put("uid", uid);
                    pressenter.sendMessage(GoodsfunctionActivity.this,Constant.OrderCompains,map,Bean.class);
                }else {
                    OkHttpUtils.post().url(Constant.PATH + Constant.OrderCompains)
                            .addParams("token", Constant.TOKEN)
                            .addParams("orderId", bean.getOrderId()+"")
                            .addParams("complainType", typeid+"")
                            .addParams("complainContent", content)
                            .addParams("uid",  SpUtils.getString(GoodsfunctionActivity.this,"uid"))
                            .files("image[]", files)
                            .build().execute(new ResultDetailCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Toast.makeText(GoodsfunctionActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(Result response, int id) {
                            Toast.makeText(GoodsfunctionActivity.this, response.getMessage(), Toast.LENGTH_LONG).show();
                            if (response != null && response.getCode() == 1) {
                                finish();
                            }
                        }
                    });

                }

                break;
            default:
        }
    }

    public String bitmapToString(Bitmap bitmap) {
        //将bitmap转换为uri
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;
    }


    private void showPopwindow() {
        View popView = View.inflate(GoodsfunctionActivity.this, R.layout.popup_questiontype, null);
        Button sure = popView.findViewById(R.id.sure);
        RecyclerView recy = popView.findViewById(R.id.recy);
        LinearLayoutManager manager = new LinearLayoutManager(GoodsfunctionActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        functionAdapter = new FunctionAdapter(GoodsfunctionActivity.this);
        functionAdapter.setaddClick(new FunctionAdapter.OnShopClick() {
            @Override
            public void item(List<FunctionBean.DataBean> beanList) {
                functionBean.setData(beanList);
                functionAdapter.setShopList(functionBean.getData());
            }
        });

        recy.setAdapter(functionAdapter);
        recy.setLayoutManager(manager);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                for (int i = 0; i < functionBean.getData().size(); i++) {
                    if (functionBean.getData().get(i).isChecked()) {
                        typeid = functionBean.getData().get(i).getDataVal() + "";
                        text_type.setText(functionBean.getData().get(i).getDataName());
                    }
                }

                if (typeid.equals("")) {
                    Toast.makeText(GoodsfunctionActivity.this, "请选择取消订单的原因", Toast.LENGTH_SHORT).show();
                    return;
                }

                popWindow.dismiss();
            }
        });


        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        pressenter.sendMessage(GoodsfunctionActivity.this, Constant.RejectReason, map, FunctionBean.class);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
                int maxNum = 5;
                MultiImageSelector selector = MultiImageSelector.create(GoodsfunctionActivity.this);
                selector.showCamera(true);
                selector.count(maxNum);
                selector.multi();
                selector.origin(mSelectPath);
                selector.start(GoodsfunctionActivity.this, REQUEST_IMAGE);
        }
    }
    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(GoodsfunctionActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                image.clear();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                    Bitmap bitmap = BitmapUtil.getScaleBitmap(p, 0, 0);
                    image.add(bitmap);
                }
                showImageAdapter.showImage(image);
            }
        }
    }


}
